#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#ifdef RVS_TEST

#include "rvs_socket.h"
#define MYPORT1	2001
#define MYPORT2	2002
#define	REPORT1	3001
#define	REPORT2	3002
#define	socket	rvs_socket
#define	close	rvs_close
#define	bind	rvs_bind
#define	sendto	rvs_sendto
#define	recvfrom	rvs_recvfrom
#define	select	rvs_select
#define	connect	rvs_connect
#define	send	rvs_send
#define	fcntl	rvs_fcntl
#define	ioctl	rvs_ioctl
#define	getsockname	rvs_getsockname

static inline void rvs_perror(const char* text)
{
    fprintf( stderr, "%s : Error = %d\n", text, rvs_errno);
}

#define	perror	rvs_perror

#else

#define MYPORT1	3001
#define MYPORT2	3002
#define	REPORT1	2001
#define	REPORT2	2002

#endif

static int sock1=-1, sock2=-1;
static struct sockaddr_in sin1, sin2, remote, local;
static int myport1=MYPORT1, myport2=MYPORT2;
static int conport1=0, conport2=0;


static int chkcmd(int cont)
{
    int sock, len, *conport, cport;
    struct sockaddr *addr;
    socklen_t addrlen = sizeof(struct sockaddr_in);
    char cmd[16];
    char buffer[2048];

    fgets(cmd, 16, stdin);

    switch(cmd[0]) {
    case 's':
    case 'S':
        fprintf (stderr, "[send] from (1)%d / (2)%d ? ", myport1, myport2);
        fgets (cmd, 16, stdin);
        if (cmd[0] == '1') {
             sock = sock1;
             cport = conport1;
        } else {
             sock = sock2;
             cport = conport2;
        }
        fprintf (stderr, "sending data >> ");
        if (fgets (buffer, 2048, stdin)) {
            if (cport == 0) {
                fprintf (stderr, "to port# > ");
                fgets (cmd, 16, stdin);
                remote.sin_port = htons(atoi(cmd));
                addr = (struct sockaddr*)&remote;
                len = sendto (sock, buffer, strlen(buffer)-1, 0, addr, addrlen);
                if (len > 0) {
                    fprintf (stderr, "sendto %s:%d\n",
                        inet_ntoa(((struct sockaddr_in*)addr)->sin_addr),
                        ntohs(((struct sockaddr_in*)addr)->sin_port));
                    fprintf( stderr, " - %.*s\n", len, buffer);
                } else {
                    perror("sendto");
                }
            } else {
                len = send (sock, buffer, strlen(buffer)-1, 0);
                if (len > 0) {
                    fprintf (stderr, "send - %.*s\n", len, buffer);
                } else {
                    perror("send");
                }
            }
        } else {
            cont = 0;
        }
        break;
    case 'c':
    case 'C':
        fprintf (stderr, "[connect] from (1)%d / (2)%d ? ", myport1, myport2);
        fgets (cmd, 16, stdin);
        if (cmd[0] == '1') {
             sock = sock1;
             conport = &conport1;
        } else {
             sock = sock2;
             conport = &conport2;
        }
        fprintf (stderr, "to port# > ");
        fgets (cmd, 16, stdin);
        *conport = atoi(cmd);
        remote.sin_port = htons(*conport);
        addr = (struct sockaddr*)&remote;
        if( connect (sock, addr, addrlen) < 0 ) {
            perror("connect");
        } else {
            fprintf (stderr, "connected to %s:%d\n",
                inet_ntoa(((struct sockaddr_in*)addr)->sin_addr),
                ntohs(((struct sockaddr_in*)addr)->sin_port));
        }
        break;
    case 'n':
    case 'N':
        fprintf (stderr, "[getsockname] (1)%d / (2)%d ? ", myport1, myport2);
        fgets (cmd, 16, stdin);
        if (cmd[0] == '1') {
             sock = sock1;
        } else {
             sock = sock2;
        }
        addr = (struct sockaddr*)&local;
        addrlen = sizeof(local);
        memset (addr, 0, addrlen);
        if (getsockname(sock, addr, &addrlen) < 0) {
            perror("getsockname");
        } else {
            fprintf(stderr, "My Address is %s:%d\n",
                inet_ntoa(((struct sockaddr_in*)addr)->sin_addr),
                ntohs(((struct sockaddr_in*)addr)->sin_port));
        }
        break;
    case 'f':
    case 'F':
        fprintf (stderr, "[fcntl] (1)%d / (2)%d ? ", myport1, myport2);
        fgets (cmd, 16, stdin);
        if (cmd[0] == '1') {
             sock = sock1;
        } else {
             sock = sock2;
        }
        fprintf (stderr, "(1)SET / (2)GET > " );
        fgets (cmd, 16, stdin);
        if (cmd[0] == '1') {
            long setv;
            fprintf (stderr, "(1)Non-Block(%#x) / (2)Block(0) > ", O_NONBLOCK );
            fgets (cmd, 16, stdin);
            if (cmd[0] == '1') setv = O_NONBLOCK;
            else setv = 0;
            if (fcntl (sock, F_SETFL, setv) < 0) {
                perror("fcntl");
            } else {
                fprintf (stderr, " ==> OK\n");
            }
        } else {
            long val = fcntl(sock, F_GETFL);
            if (val < 0) {
                perror("fcntl");
            } else {
                fprintf (stderr, " ==>%#x\n", (unsigned int)val);
            }
        }
        break;
    case 'i':
    case 'I':
        fprintf (stderr, "[ioctl] (1)%d / (2)%d ? ", myport1, myport2);
        fgets (cmd, 16, stdin);
        if (cmd[0] == '1') {
             sock = sock1;
        } else {
             sock = sock2;
        }
        fprintf (stderr, "(%d)FIONBIO / ... > ", FIONBIO );
        fgets (cmd, 16, stdin);
        {
            int request = atoi(cmd);
            long setv;

            fprintf (stderr, "Value > ");
            fgets (cmd, 16, stdin);
            setv = atoi(cmd);
            if (ioctl (sock, request, &setv) < 0) {
                perror("ioctl");
            } else {
                fprintf (stderr, " ==> OK\n");
            }
        }
        break;
    case 'q':
    case 'Q':
        cont=0;
        break;
    }

    return cont;
}

static int recv_packet(int sock, int cont)
{
    int len;
    char buffer[2048];
    struct sockaddr_in from;
    socklen_t fromlen = sizeof(from);

    if ((len = recvfrom(sock, buffer, 2048, 0,
                      (struct sockaddr*)&from, &fromlen)) < 0) {
        perror("recvfrom");
        return 0;
    }
    if (len == 0) cont=0;
    fprintf( stderr, "recvfrom(sock%d) %s:%d\n",
           (sock==sock1)?1:2,
           inet_ntoa(from.sin_addr), ntohs(from.sin_port));
    fprintf( stderr, " - %.*s\n", len, buffer);

    return cont;
}

void usage(char* cmd)
{
#define USAGE	"\
[USAGE]\n\
    %s [-1 <myport1>][-2 <myport2>][-h]\n"

    fprintf(stderr, USAGE, cmd);
}

int main(int argc, char** argv)
{
    int cont;
    int nev;
    fd_set readfds, rvreadfds;
    int nfds, rvnfds=0;
    char *prog = argv[0];
    struct timeval atv = { 30, 0 };

    for (argc--, argv++; argc>0; argc--, argv++) {
        if (**argv != '-') {
            usage(prog);
            exit(1);
        }
        switch (*(*argv+1)) {
        case '1':
            argc--; argv++;
            myport1 = atoi(*argv);
            break;
        case '2':
            argc--; argv++;
            myport2 = atoi(*argv);
            break;
        case 'w':
            argc--; argv++;
            {
                char* next=strchr(*argv, ':');
                if (next) {
                    *next++ = 0;
                    atv.tv_usec = atoi(next);
                }
                atv.tv_sec = atoi(*argv);
            }
            break;
        default:
            usage(prog);
            exit(1);
        }
    }

    fprintf (stdout, "===== %s Started: MyPort#1=%d, MyPort#2=%d =====\n",
            prog, myport1, myport2);

    sock1 = socket (AF_INET, SOCK_DGRAM, 0);
    if (sock1 < 0) {
        perror("socket");
        goto sockerr;
    }
    sock2 = socket (AF_INET, SOCK_DGRAM, 0);
    if (sock2 < 0) {
        perror("socket");
        goto sockerr;
    }

    memset (&sin1, 0, sizeof(sin1));
    memset (&sin2, 0, sizeof(sin2));
    memset (&remote, 0, sizeof(remote));
    remote.sin_family = sin2.sin_family = sin1.sin_family = AF_INET;
    sin2.sin_addr.s_addr = sin1.sin_addr.s_addr = INADDR_ANY;
    remote.sin_addr.s_addr = inet_addr("127.0.0.1");
    sin1.sin_port = htons(myport1);
    sin2.sin_port = htons(myport2);
    remote.sin_port = htons(REPORT1);

    if (bind (sock1, (struct sockaddr*)&sin1, sizeof(sin1)) < 0) {
        perror("bind");
        goto sockerr;
    }
    if (bind (sock2, (struct sockaddr*)&sin2, sizeof(sin2)) < 0) {
        perror("bind");
        goto sockerr;
    }

    cont=1;
    while (cont) {
        FD_ZERO(&rvreadfds);
        FD_SET(sock1, &rvreadfds);
        FD_SET(sock2, &rvreadfds);
        rvnfds = (sock1>sock2)?(sock1+1):(sock2+2);
        FD_ZERO(&readfds);
        FD_SET(0,&readfds);  /* 標準入力 */
        nfds = 1;
        struct timeval tv;

        fprintf (stderr, "[s/r] > ");

        memcpy (&tv, &atv, sizeof(struct timeval));
        nev = rvs_select_multi (rvnfds, &rvreadfds, NULL, NULL, 
                                nfds, &readfds, NULL, NULL, &tv);
        if (nev < 0) {
            fprintf(stderr, "\n");
            perror("select");
            break;
        } else if (nev == 0) {
            fprintf( stderr, "\nselect: Timeout\n");
            continue;
        }

        if (FD_ISSET(0,&readfds)) {
            cont = chkcmd(cont);
            if (--nev == 0) continue;
        }

        if (FD_ISSET(sock1, &rvreadfds)) {
            cont = recv_packet(sock1, cont);
            if (--nev == 0) continue;
        }

        if (FD_ISSET(sock2, &rvreadfds)) {
            cont = recv_packet(sock2, cont);
            if (--nev == 0) continue;
        }

    }

    close(sock1);
    close(sock2);

    return 0;

sockerr:
    if (sock1 >= 0) close(sock1);
    if (sock2 >= 0) close(sock2);
    exit(1);
}

